//
//  ZSLRScrollView.m
//  CheFu365
//
//  Created by safiri on 2017/12/14.
//  Copyright © 2017年 safiri. All rights reserved.
//

#import "ZSLRPageScrollView.h"

@interface ZSLRPageScrollView ()<UIScrollViewDelegate>

@property (nonatomic ,assign ,readwrite) NSInteger currentPage;
//移动系数
@property (nonatomic ,assign ,readwrite) CGFloat scrollRatio;

@end

@implementation ZSLRPageScrollView

#pragma mark - init

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self config];
    }
    return self;
}

- (void)config {
    self.isHorizontallyScroll = YES;
    self.alwaysBounceHorizontal = NO;
    self.bounces = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.delegate = self;
}

- (void)setForbiddenScrollEnabled:(BOOL)forbiddenScrollEnabled {
    _forbiddenScrollEnabled = forbiddenScrollEnabled;
    self.scrollEnabled = !forbiddenScrollEnabled;
}

- (void)scrollToPage:(NSInteger)page animated:(BOOL)animated completion:(void (^)(BOOL))completion {
    if (page >= self.allViewsCount) return;
    
    self.currentPage = page;
    CGFloat duration = animated?0.5:0;
    [UIView animateWithDuration:duration animations:^{
        self.contentOffset = CGPointMake(page * self.frame.size.width, 0);
    } completion:completion];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //NSLog(@"scrollView.contentOffset.x - %f",scrollView.contentOffset.x);
    //NSLog(@"%f",scrollView.contentOffset.x/self.frame.size.width);
   
    self.scrollRatio = scrollView.contentOffset.x/self.frame.size.width;
    if ([self.lrPageScrollViewDelegate respondsToSelector:@selector(lrPageScrollView:scrollRatio:)]) {
        [self.lrPageScrollViewDelegate lrPageScrollView:self scrollRatio:self.scrollRatio];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger page = scrollView.contentOffset.x / self.frame.size.width;
   
    if (self.currentPage != page) {
        self.currentPage = page;
        if ([self.lrPageScrollViewDelegate respondsToSelector:@selector(lrPageScrollView:changePage:)]) {
            [self.lrPageScrollViewDelegate lrPageScrollView:self changePage:self.currentPage];
        }
    }
}


//解决UIScrollView与左滑手势的冲突
//如果这个手势没有被识别，那么就多个gestureRecognizer可以同步识别
//-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
//    if (gestureRecognizer.state != 0) {
//        return YES;
//    }else {
//        return NO;
//    }
//}

@end
